<?php
namespace app\admin\controller;
use think\Db;
use app\home\controller\Renew as RenewAct;
class Renew extends Base
{

    public function index(){
        $count = Db::name('novel')
            ->where('status','=',1)
            ->where('serialize','=',0)
            ->field('id')
            ->select();
        $list = $this->records();
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->assign('meta_title','更新小说');
        return $this->fetch();
    }

    public function records(){
        $dir = './runtime/log/renew';
        if(!is_dir($dir)) mkdir($dir, 0755);

        $time = input('get.renew_time')??0;
        if($time){
            $file = $dir.'/record'.$time.'.txt';
            $string = file_get_contents($file);
            $info = ['renew_time'=>$time];
            $this->assign('info',$info);
            $this->assign('record',$string);
            $this->assign('meta_title','查看更新日志');
            return $this->fetch();
        }

        $handler = opendir($dir);
        $data=[];
        while (($filename = readdir($handler)) !== false) {//务必使用!==，防止目录下出现类似文件名“0”等情况
            if ($filename != "." && $filename != "..") {
                if (substr($filename,-4)=='.php'){
                    $data[] = unserialize(file_get_contents($dir.'/'.$filename));
                }
            }
        }

        closedir($handler);
        array_multisort(array_column($data,'renew_time'),SORT_DESC,$data);
        return $data;
    }

    public function renew(){
        if(input('get.')){
            //检测是否有任务在执行做了锁定
            $dir = './runtime/log/renew';
            if(!is_dir($dir)) mkdir($dir, 0755);
            $lockFile = $dir.'/processing.lock';
            if(is_file($lockFile)) $this->error('有一项小说更新任务正在执行，请稍后重试！');

            //开始执行
            $startPage = input('get.start_page')?input('get.start_page'):1;
            $endPage = input('get.end_page')?input('get.end_page'):0;
            $limit = input('get.limit')?input('get.limit'):50;
            $type = input('get.type')?true:false;

            if($endPage && $startPage > $endPage ) $this->error('结束页不能小于开始页');

            $msg = $type?'开始手动更新':'开始全量更新';
            $rs = ['code' => 1, 'msg' => $msg, 'data' => [$startPage,$endPage,$limit,$type], 'url'=>url('index'), 'wait'=>3];

            echo json_encode($rs);// 输出结果到前端
            set_time_limit(5);
            $renewKey = Db::name("Config")
                ->where('name','=','auto_renew_key')
                ->value('value');
            //提交刷新请求
            $Renew = new RenewAct();
            $Renew->index($renewKey,$startPage,$endPage,$limit,$type);

        }else{
            $field = ['type','start_page','end_page','limit',];
            $this->assign('field',$field);
            $this->assign('meta_title','手动更新小说');
            return $this->fetch();
        }
    }

    public function del(){
        $dir = './runtime/log/renew';
        if(!is_dir($dir)) $this->error('日志目录不存在。');

        $time = input('get.renew_time');

        if(!$time) $this->error('请求出错，请确认提交正确。');

        if($time === 'all'){
            $this->delAllFiles($dir);
            $this->success('已清空日志目录下所有日志数据！');
        }

        $recordFile = $dir.'/record'.$time.'.txt';
        $dataFile = $dir.'/renew_data'.$time.'.php';
        $re1 = unlink($recordFile);
        $re2 = unlink($dataFile);
        $re1 && $re2?$this->success('删除成功！') : $this->error('删除失败！');
    }

    public function delAllFiles($dir) {
        //先删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullPath=$dir."/".$file;
                if(!is_dir($fullPath)) {
                    unlink($fullPath);
                } else {
                    $this->delAllFiles($fullPath);
                }
            }
        }
        closedir($dh);
    }
    public function get_processing(){
        $dir = './runtime/log/renew';
        if(!is_dir($dir)) mkdir($dir, 0755);
        //检测任务锁定
        $lockFile = $dir.'/processing.lock';
        if(is_file($lockFile)) {
            $process = unserialize(file_get_contents($lockFile));
            $this->success('当前有正在执行的任务','',$process);
        }else{
            $this->error('没有正在执行的任务');
        }

    }

}